package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    private Logger logger = Logger.getLogger(UserController.class);


    @RequestMapping(value = "/getUserList.html")
    public String getList(@RequestParam(value = "queryname",required = false) String queryname,
                          @RequestParam(value = "queryUserRole",required = false) Integer queryUserRole,
                          @RequestParam (value = "pageIndex", required = false,defaultValue = "1") Integer PageNo,
                          @RequestParam(value = "pageSize", required = false,defaultValue = "5") Integer pageSize,
                          Model model){


        //总数量（表）
        Integer totalCount = userService.getUserCount(queryname,queryUserRole);

        int totalPageCount = totalCount/pageSize;
        if(totalCount%pageSize!=0){
            totalPageCount++;
        }

        //控制首页和尾页
        if(PageNo < 1){
            PageNo = 1;
        }else if(PageNo > totalPageCount){
            PageNo = totalPageCount;
        }





        List<Role> roleList = roleService.getRoleList();
        List<User> userList = userService.getUserList(queryname,queryUserRole,PageNo,pageSize);
        model.addAttribute("userList",userList);
        model.addAttribute("roleList",roleList);

        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", PageNo);

        return "userlist";
    }


    @RequestMapping(value = "/toAdd.html")
    public String toAdd(Model model){
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        return "useradd";
    }




    @RequestMapping(value = "/add.html",method = RequestMethod.POST)
    public String add(User user, HttpServletRequest request,
                      HttpSession session,HttpServletResponse response,
                      @RequestParam(value = "attachs",required = false) MultipartFile[] attachs)throws IOException {
        String idPicPath = null;
        String workPicPath = null;

        String filtname = null;
        String errorInfo = null;

        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];


            //文件上传
            if(attachs!=null){

                if(i==0){
                    errorInfo = "uploadFileError";
                }else if(i==1){
                    errorInfo = "uploadWpError";
                }


                //判断文件大小
                if(attach.getSize()>5000000){
                    request.setAttribute(errorInfo,"*上传大小不得超过5000kb");
                    return "useradd";
                }
                //判断文件格式
                if (!(attach.getOriginalFilename().endsWith("jpg")||
                        attach.getOriginalFilename().endsWith("png")||
                        attach.getOriginalFilename().endsWith("jpeg")||
                        attach.getOriginalFilename().endsWith("pneg"))){
                    request.setAttribute(errorInfo,"*上传失败");
                    return "useradd";
                }
                //文件上传到哪里？目标路径
                String path = session.getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");

                File targetFile = null;
                if(i==0){
                    //文件名
                    idPicPath = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";

                    String filePath = path+File.separator+idPicPath;

                    targetFile = new File(filePath);
                }
                if(i==1){
                    //文件名
                    workPicPath = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";

                    String filePath = path+File.separator+workPicPath;

                    targetFile = new File(filePath);
                }


                //判断目标是否存在
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }

                //把文件传输到目标文件
                attach.transferTo(targetFile);



            }

        }
        user.setIdPicPath(idPicPath);
        user.setWorkPicPath(workPicPath);
        user.setCreationDate(new Date());

        boolean check = userService.add(user);
        if(check){
            return "redirect:/user/getUserList.html";
        }
        return "useradd";
    }

    @RequestMapping(value = "/view/{id}")
    public String getUserById(Model model,
                              @PathVariable(value = "id") Integer id){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "userview";

    }

    @RequestMapping(value = "/modifyUser/{id}")
    public String toModifyUser(Model model,
                             @PathVariable(value = "id") Integer id){
        User user = userService.getUserById(id);
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("user",user);
        model.addAttribute("roleList",roleList);
        return "usermodify";
    }

    @RequestMapping(value = "/modifyUser.html",method = RequestMethod.POST)
    public String modifyUser(User user){
        boolean check = userService.modify(user);

        if(!check){
            return "usermodify";
        }
        return "redirect:/user/getUserList.html";

    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(value = "id") Integer id){
        boolean check = userService.delete(id);
        HashMap<String,String> data = new HashMap<String,String>();
        if(id!=null){
            if(check){
                data.put("delResult","true");
            }else{
                data.put("delResult","false");
            }
        }else{
            data.put("delResult","notexist");
        }

        return JSONArray.toJSONString(data);
    }

    @RequestMapping(value = "/getUserCode")
    @ResponseBody
    public Object getUserCode(@RequestParam(value = "userCode") String userCode){
        User user = userService.getUserCode(userCode);
        HashMap<String,String> data = new HashMap<String,String>();

        if(user!=null){
            data.put("userCode","exist");
        }else{
            data.put("userCode","true");
        }


        return JSONArray.toJSONString(data);
    }

    @RequestMapping(value="/view",method=RequestMethod.GET)
    @ResponseBody
    public User view(@RequestParam Integer id){
        logger.debug("view id: "+id);
        User user = new User();
        try {
            user = userService.getUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @RequestMapping(value = "/pwdmodify.html")
    public String pwdmodify(HttpSession session){
        User user = (User)session.getAttribute("userSession");

        return "pwdmodify";
    }

    @RequestMapping(value = "/getPwdModify")
    @ResponseBody
    public Object getPwdModify(@RequestParam(value = "oldpassword") String oldpassword,
                               HttpSession session){
        User user = (User)session.getAttribute("userSession");


        HashMap<String,String> data = new HashMap<String,String>();

        if(user==null){
            data.put("result","sessionerror");
        }else
        if(oldpassword==null){
            data.put("result","error");
        }else if(!user.getUserPassword().equals(oldpassword)){
            data.put("result","false");
        }else {
            data.put("result","true");
        }

        return JSONArray.toJSONString(data);
    }


    @RequestMapping(value = "/userPwdUpdate",method = RequestMethod.POST)
    public String userPwdUpdate(HttpSession session,
                                @RequestParam(value = "newpassword")String newpassword){
        User user = (User)session.getAttribute("userSession");

        boolean check = userService.pwdUpdate(newpassword,user.getId());

        if(check){
            return "/frame";
        }
        return "redirect:/user/pwdmodify.html";
    }


}